/**
 * @file procedures.c
 * @brief Short description of this file.
 *
 * Complete description of this file.
 *
 * @date Mar 19, 2012
 * @author Francesco Corvino
 */
#include "procedures.h"
#include <unistd.h>

void startProc() {
	pid_t pid;
    if ((pid = fork()) < 0) {
    	printf("Errore nel creare la nuova sessione!");
    } else if (pid == 0) {      /* child */
    	execlp("./startApp", (char *)0);
    	exit(0);
    }
}

int _Chat_waitInput(int fd0, int fd1){
	struct timeval tv;
	tv.tv_sec = 1000; tv.tv_usec = 0;
	fd_set fdsetread;
	FD_ZERO(&fdsetread);
	FD_SET(fd0,&fdsetread);
	FD_SET(fd1, &fdsetread);
	int maxfd = (fd0>fd1)?(fd0):(fd1);
	select(maxfd+1,&fdsetread,NULL,NULL,&tv);
	if(FD_ISSET(fd0,&fdsetread)) return 0;
	else if(FD_ISSET(fd1,&fdsetread)) return 1;
	return -1;
}

void regTerminal(char *pathToRegPipe){
	char msg[255];
	pid_t mypid = getpid();
	sprintf(msg,"newsession %d ", mypid);

	InterfaceFifo regFifo;
	memcpy(regFifo.name,pathToRegPipe,strlen(pathToRegPipe));
	regFifo.openmode = O_WRONLY;
	printf("Open fifo to %s\n",pathToRegPipe);

	InterfaceFifo_createFifo(pathToRegPipe);

	InterfaceFifo_startComm(&regFifo);

	InterfaceFifo_sendMsg(&regFifo,msg);

	InterfaceFifo_closeComm(&regFifo);
}

void startCommunication(InterfaceFifo *fin, InterfaceFifo *fout){
	// crea 2 fifo
	fin->openmode = O_RDWR;//ONLY;

	fout->openmode = O_RDWR;//ONLY;

	puts("creazione delle fifo\n");
	InterfaceFifo_createFifo(fin->name);
	InterfaceFifo_createFifo(fout->name);

	puts("apertura delle fifo\n");
	InterfaceFifo_startComm(fout);
	InterfaceFifo_startComm(fin);
}
